﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Adams.Web.Areas.MyAdams.Logic.Profile
{
    public static class Email
    {
        public static MyAdams.Models.Profile.Email.PageLoad PageLoad(int memberid)
        {
            return MyAdams.Data.Profile.Email.PageLoad(memberid);
        }

        public static Adams.Web.Models.FormOutput SaveEmail(int memberid, Adams.Web.Areas.MyAdams.Models.Profile.Email.FormInput input)
        {
            var output = Adams.Web.Logic.Validation.PerformBasicValidation(input);

            if (output.IsValid)
            {
                var memberinfo = MyAdams.Data.Profile.Email.GetMemberInfo(memberid, input.Email);
                if (!Shared.Str.IsEqual(input.Email, memberinfo.Email))
                {
                    if (memberinfo.Exists)
                    {
                        output.InvalidFields.Add(new Adams.Web.Models.InvalidField() { Name = "Email", Code = 4 });
                    }
                }

                if (output.IsValid)
                {
                    MyAdams.Data.Profile.Email.SaveEmail(memberid, input.Email);
                    output.IsSaved = true;

                    string subject = "Confirm your ADAMS account";
                    string from = Shared.Config.GetAppSetting("SecurityFromEmail");
                    string body = Adams.Web.Logic.Email.GenerateChangeEmail(input.Email);
                    Adams.Web.Logic.Email.QueueEmail(subject, from, input.Email, body, 1);
                }
            }

            return output;
        }
    }
}